package com.rabbiter.library.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.rabbiter.library.annotation.Auth;
import com.rabbiter.library.jwt.JwtUtils;
import com.rabbiter.library.utils.ResultUtils;
import com.rabbiter.library.utils.ResultVo;
import com.rabbiter.library.entity.SysReader;
import com.rabbiter.library.service.SysReaderService;
import com.rabbiter.library.service.SysRoleService;
import com.rabbiter.library.dto.PageParm;
import com.rabbiter.library.entity.SysUser;
import com.rabbiter.library.dto.UpdatePasswordParm;
import com.rabbiter.library.service.SysUserService;
import com.rabbiter.library.entity.UserRole;
import com.rabbiter.library.service.UserRoleService;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Api(tags = "系统用户管理接口")
@RestController
@RequestMapping("/api/user")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private SysReaderService sysReaderService;

    @ApiOperation(value = "添加用户", notes = "添加新的系统用户")
    @Auth
    @PostMapping
    public ResultVo addUser(@RequestBody SysUser user){
        //判断账户是否被占用
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.lambda().eq(SysUser::getUsername,user.getUsername());
        SysUser one = sysUserService.getOne(query);
        if(one != null){
            return ResultUtils.error("账户被占用!");
        }
        //密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        //设置是否是管理员
        user.setIsAdmin("0");
        user.setCreateTime(new Date());
        //入库
        sysUserService.addUser(user);
        return ResultUtils.success("新增用户成功!");
    }

    @ApiOperation(value = "编辑用户", notes = "更新系统用户信息")
    @Auth
    @PutMapping
    public ResultVo editUser(@RequestBody SysUser user){
        //判断账户是否被占用
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.lambda().eq(SysUser::getUsername,user.getUsername());
        SysUser one = sysUserService.getOne(query);
        if(one != null && one.getUserId() != user.getUserId()){
            return ResultUtils.error("账户被占用!");
        }
        //密码加密
//        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setUpdateTime(new Date());
        //更新
        sysUserService.editUser(user);
        return ResultUtils.success("编辑用户成功!");
    }

    @ApiOperation(value = "删除用户", notes = "根据ID删除系统用户")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataTypeClass = Long.class, paramType = "path")
    @Auth
    @DeleteMapping("/{userId}")
    public ResultVo delete(@PathVariable("userId") Long userId){
        boolean remove = sysUserService.removeById(userId);
        if(remove){
            return ResultUtils.success("删除用户成功!");
        }
        return ResultUtils.error("删除用户失败!");
    }

    @ApiOperation(value = "用户列表", notes = "分页查询系统用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "当前页码", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "username", value = "用户名", dataTypeClass = String.class),
            @ApiImplicitParam(name = "phone", value = "手机号", dataTypeClass = String.class)
    })
    @Auth
    @GetMapping("/list")
    public ResultVo getList(PageParm parm){
        IPage<SysUser> list = sysUserService.list(parm);
        //密码处理
        list.getRecords().stream().forEach(item ->{
            item.setPassword("");
        });
        return ResultUtils.success("查询成功",list);
    }

    @ApiOperation(value = "获取角色列表", notes = "获取所有角色，用于分配角色")
    @Auth
    @GetMapping("/getRoleList")
    public ResultVo getRoleList(){
        List<SysReader.SysRole> list = sysRoleService.list();
        return ResultUtils.success("查询成功",list);
    }

    @ApiOperation(value = "获取用户角色", notes = "根据用户ID获取已分配的角色")
    @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataTypeClass = Long.class)
    @Auth
    @GetMapping("/getRoleId")
    public ResultVo getRoleId(Long userId){
        QueryWrapper<UserRole> query = new QueryWrapper<>();
        query.lambda().eq(UserRole::getUserId, userId);
        UserRole one = userRoleService.getOne(query);
        return ResultUtils.success("查询成功",one);
    }

    @ApiOperation(value = "修改密码", notes = "用户修改自己的密码")
    @Auth
    @PostMapping("/updatePassword")
    public ResultVo updatePassword(@RequestBody UpdatePasswordParm parm, HttpServletRequest request){
        //获取token
        String token = request.getHeader("token");
        Claims claims = jwtUtils.getClaimsFromToken(token);
        Object userType = claims.get("userType");
        //原密码
        String old = DigestUtils.md5DigestAsHex(parm.getOldPassword().getBytes());
        if(userType.equals("0")){ //0 ：读者
            SysReader reader = sysReaderService.getById(parm.getUserId());
            //密码对比
            if(!old.equals(reader.getPassword())){
                return ResultUtils.error("原密码错误!");
            }
            SysReader sysReader = new SysReader();
            sysReader.setPassword(DigestUtils.md5DigestAsHex(parm.getPassword().getBytes()));
            sysReader.setReaderId(parm.getUserId());
            boolean b = sysReaderService.updateById(sysReader);
            if(b){
                return ResultUtils.success("密码修改成功!");
            }
        }else{ // 管理员
            SysUser user = sysUserService.getById(parm.getUserId());
            if(!user.getPassword().equals(old)){
                 return ResultUtils.error("原密码错误!");
            }
            SysUser sysReader = new SysUser();
            sysReader.setPassword(DigestUtils.md5DigestAsHex(parm.getPassword().getBytes()));
            sysReader.setUserId(parm.getUserId());
            boolean b = sysUserService.updateById(sysReader);
            if(b){
                return ResultUtils.success("密码修改成功!");
            }
        }
        return ResultUtils.error("密码修改失败!");
    }

    @ApiOperation(value = "重置密码", notes = "管理员重置用户密码为默认密码123456")
    @PostMapping("/resetPassword")
    public ResultVo resetPassword(@RequestBody SysUser sysUser){
        String password = "123456";
        sysUser.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        boolean b = sysUserService.updateById(sysUser);
        if(b){
            return ResultUtils.success("重置密码成功!");
        }
        return ResultUtils.error("重置密码失败!");
    }
}
